package com.ibeeking.found.msg.rest.service.mpevent;

import com.ibeeking.found.msg.rest.service.IWxMpMenuService;
import com.ibeeking.found.msg.rest.service.IWxMpMsgService;
import com.ibeeking.found.msg.service.common.bo.WxMpMenuBO;
import com.ibeeking.found.msg.service.common.param.WxMpAutoMsgParam;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import me.chanjar.weixin.mp.builder.outxml.TextBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;


/**
 * 菜单handler
 *
 * @Author ibeeking
 */
@Component
public class MenuHandler  implements WxMpMessageHandler {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private IWxMpMenuService mpMenuServiceImpl;
    @Resource
    private IWxMpMsgService wxMsgServiceImpl;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        //消息记录
        if (WxConsts.EventType.CLICK.equals(wxMessage.getEvent())) {
            WxMpMenuBO menuBO = mpMenuServiceImpl.queryMenuById(Long.valueOf(wxMessage.getEventKey()));
            if (menuBO != null) {
                WxMpXmlOutTextMessage out = new TextBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).content(menuBO.getUnionKey()).build();
                record(wxMessage, menuBO.getAppId(), menuBO.getUnionKey(), out);
                return out;
            }
        }
        String content = "工程师熬夜中！";
        return new TextBuilder().content(content).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
    }

    private void record(WxMpXmlMessage wxMessage, String appId, String unionKey, WxMpXmlOutTextMessage out) {
        WxMpAutoMsgParam param = new WxMpAutoMsgParam();
        param.setAppId(appId);
        param.setOpenId(wxMessage.getFromUser());
        param.setRepType(wxMessage.getMsgType());
        param.setRepEvent(wxMessage.getEvent());
        param.setUnionKey(unionKey);
        param.setReturnType(out.getMsgType());
        param.setRepContent(wxMessage.getContent());
        wxMsgServiceImpl.add(param);
    }
}
